import requests,aiohttp,asyncio,aiofiles,json,re,demjson,ast,os
from lxml import etree



# https://lol.52pk.com/pifu/hero/7323384.shtml
# https://lol.52pk.com/pifu/hero/7323384.shtml
# https://pic2.52pk.com/   + \/files\/allimg\/190625\/N12246_1F53R2Q.jpg    replace('\','')

'''
1,获取页面源代码
2，

'''

def down(url):
    res = requests.get(url)
    print('3')

    return res

async def aio_down_pic(url,name):
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "DNT": "1",
        "If-Modified-Since": "Mon, 01 Apr 2019 08:31:47 GMT",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.54",
        "sec-ch-ua": "^\\^Chromium^^;v=^\\^104^^, ^\\^",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "^\\^Windows^^"
    }
    cookies = {
        "Hm_lvt_1bb50e722c394304064bf1ce3aa578b6": "1659671055,1660746598"
    }
    async with aiohttp.ClientSession() as session:
        async with session.get(url,headers=headers,cookies=cookies) as cont:
            print(cont)
            async with aiofiles.open(f'img/{name}.jpg',mode='wb') as pic:
                await pic.write(await cont.content.read())
    pass

async def func(res):
    tasks = []
    for response in res:
       try:
            res = json.loads(response)
            title = res['title']
            hero = res['ssyx']
            pic_url = 'https://pic2.52pk.com/' + ''.join(res['skinbigpic']).replace('\/', '/')
            name = ''.join(hero + '-' + title).replace('/','-')
            d = asyncio.create_task(aio_down_pic(pic_url,name))
            tasks.append(d)
       except:
           continue
    await asyncio.wait(tasks)
    # print(hero+'-'+title)


if __name__ == '__main__':
    url = 'https://lol.52pk.com/data/skin.js'
    res = down(url).text[16:-1]    # [{},{},{}]

    path = 'img'
    if os.path.exists(path) is False:
        os.mkdir(path)

    res = res.replace('},{','}cnmcnmcnm{').split('cnmcnmcnm')  # 字符切片成列表

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(func(res))

    for dirpath, dirnames, filenames in os.walk(path):
        for file in filenames:
            file_tmp = os.path.join(dirpath, file)
            file_size = os.path.getsize(file_tmp)
            if (file_size < 10240):  # size<10KB的话，删除文件
                os.remove(file_tmp)